<template>
  <!-- 拖拽组件 -->
  <div class="config-draggable">
    <div class="config-container">
      <transition-group name="sort" class="config-item-list">
        <div
          class="config-item p-2"
          v-for="app in dragList"
          :key="app.id"
          :draggable="true"
          @dragstart="dragstart(app)"
          @dragenter="dragenter(app, $event)"
          @dragend="getDragend(dragList, 'customer', $event)"
        >
          <div>
            <img class="icon_a" v-if="app.logo" :src="app.logo" />
            <div class="ellipsis">{{ app.name }}</div>
          </div>
        </div>
      </transition-group>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    /**
     * [{
     * id:xxx,
     * name:xxx
     * }]
     */
    dragList: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {
      oldData: [],
      newData: [],
      dragStartId: "",
      dragEndId: "",
    };
  },

  mounted() {},

  methods: {
    dragstart(value) {
      this.oldData = value;
      this.dragStartId = value.id;
    },
    dragenter(value) {
      this.newData = value;
      this.dragEndId = value.id;
    },
    getDragend(listData, type) {
      if (this.oldData !== this.newData) {
        let oldIndex = listData.indexOf(this.oldData);
        let newIndex = listData.indexOf(this.newData);
        let newItems = [...listData];
        // 删除之前DOM节点
        newItems.splice(oldIndex, 1);
        // 在拖拽结束目标位置增加新的DOM节点
        newItems.splice(newIndex, 0, this.oldData);
        // 每次拖拽结束后，将拖拽处理完成的数据，赋值原数组，使DOM视图更新，页面显示拖拽动画
        this.dragList.length = 0;
        newItems.forEach((item) => this.dragList.push(item));
        // 每次拖拽结束后调用接口时时保存数据
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.config-item-list {
  display: flex;
  align-items: center;
  justify-content: center;
  column-gap: 20px;
  .config-item {
    background-color: aquamarine;
    color: #fff;
  }
}
.sort-move {
  transition: transform 1s;
}
</style>
